<template>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item prop="foundLocationId">
        <el-select v-model="queryParams.actualQuantity" placeholder="请选择盘点状态" style="width:300px">
          <el-option label="正常" value="1"/>
          <el-option label="异常" value="0"/>
        </el-select>
        <el-button type="primary" :icon="Search" :style="$globalAttribute.primaryButton" @click="handleQuery">搜索
        </el-button>
        <el-button :icon="Refresh" type="primary" plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" table-layout="auto" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column prop="assetCode" label="资产编号" align="left"/>
      <el-table-column prop="name" label="资产名称" align="center"/>
      <el-table-column prop="status" label="资产状态" align="center">
        <template #default="scope">
          <el-tag color="#0ACF83" style="color: #fff;" v-if="scope.row.status===0">闲置</el-tag>
          <el-tag type="primary" v-if="scope.row.status===1">领用中</el-tag>
          <el-tag type="success" v-if="scope.row.status===2">使用中</el-tag>
          <el-tag type="warning" v-if="scope.row.status===3">维修中</el-tag>
          <el-tag type="danger" v-if="scope.row.status===4">已报废</el-tag>
          <el-tag type="info" v-if="scope.row.status===5">其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="盘点状态" align="center">
        <template #default="scope">
          <el-link type="warning" v-if="scope.row.actualQuantity==='0'">未确认</el-link>
          <el-link type="success" v-if="scope.row.actualQuantity==='1'">正常</el-link>
        </template>
      </el-table-column>

      <el-table-column prop="principalName" label="负责人" align="center"/>
      <el-table-column prop="model" label="资产型号" align="center"/>
      <el-table-column prop="categoryName" label="所属分类" align="center"/>
      <el-table-column prop="deptName" label="仓库" align="center"/>
      <el-table-column prop="locationName" label="位置" align="center"/>
      <el-table-column prop="serialNumber" label="设备序列号" align="center"/>
      <el-table-column prop="batchNumber" label="批次号" align="center"/>
      <el-table-column prop="purchaseCost" label="采购成本" align="center"/>
      <el-table-column prop="purchaseDate" label="采购日期" align="center"/>

      <el-table-column label="资产照片" align="center" width="120">
        <template #default="scope">
          <el-image :lazy="true" :src="'http://localhost:8081/'+scope.row.pic"
                    :preview-src-list="['http://localhost:8081/'+scope.row.pic]" :z-index="999999"
                    :preview-teleported="true" style="width: 40px;height:40px;"></el-image>
          <!--          <el-image :lazy="true" :src="scope.row.pic"-->
          <!--                    :preview-src-list="[scope.row.pic]" :z-index="999999"-->
          <!--                    :preview-teleported="true" style="width: 40px;height:40px;"></el-image>-->
        </template>
      </el-table-column>
      <!--      <el-table-column prop="assigned_to" label="领用人" width="120"/>-->

      <!-- <el-table-column label="实际位置ID" align="center" prop="foundLocationId" /> -->
      <!-- <el-table-column label="实际数量" align="center" prop="actualQuantity" /> -->
       <!-- 0-闲置 1-使用中 2-维修中 3-已报废 4-已处置 -->
      <!--      <el-table-column label="实际状态" align="center" prop="actualStatus"/>-->
      <el-table-column label="差异数量" align="center" prop="difference"/>
      <el-table-column label="差异说明" align="center" prop="discrepancyNote" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" :icon="Edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['check:detail:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改盘点单明细对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="detailRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="盘点单ID" prop="checkId" v-show="false">
          <el-input v-model="form.checkId" placeholder="请输入盘点单ID" />
        </el-form-item>
        <el-form-item label="资产ID" prop="assetId" v-show="false">
          <el-input v-model="form.assetId" placeholder="请输入资产ID" />
        </el-form-item>
        <el-form-item label="实际位置ID" prop="foundLocationId" v-show="false">
          <el-input v-model="form.foundLocationId" placeholder="请输入实际位置ID" />
        </el-form-item>
        <el-form-item label="位置ID" prop="locationId" v-show="false">
          <el-input v-model="form.locationId" placeholder="请输入位置ID" />
        </el-form-item>
        <el-form-item label="差异数量" prop="difference">
          <el-input v-model="form.difference" placeholder="请输入差异数量" />
        </el-form-item>
        <el-form-item label="盘点状态" prop="actualQuantity">
          <el-select v-model="form.actualQuantity" placeholder="请选择盘点状态" style="width: 100%">
            <el-option label="正常" value="1"/>
            <el-option label="异常" value="0"/>
          </el-select>
        </el-form-item>
        <el-form-item label="差异说明" prop="discrepancyNote">
          <el-input v-model="form.discrepancyNote" placeholder="请输入差异说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>

</template>

<script setup name="Detail">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue'
import {checkAssetList, listDetail, getDetail, delDetail, addDetail, updateDetail } from "@/api/InventoryCheckDetail";

import { useRoute } from 'vue-router';
import {Edit, Refresh, Search} from "@element-plus/icons-vue";



const route = useRoute()
const { proxy } = getCurrentInstance();
const detailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    checkId: null,
    assetId: null,
    foundLocationId: null,
    locationId: null,
    systemQuantity: null,
    actualQuantity: null,
    status: null,
    difference: null,
    batchNo: null,
    discrepancyNote: null
  },
  rules: {
    checkId: [
      { required: true, message: "盘点单ID不能为空", trigger: "blur" }
    ],
    assetId: [
      { required: true, message: "资产ID不能为空", trigger: "blur" }
    ],
    systemQuantity: [
      { required: true, message: "系统数量不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
queryParams.value.checkId = ref(route.query.id)
/** 查询盘点单明细列表 */
function getList() {
  loading.value = true;
  checkAssetList({checkId: route.query.id}).then(response => {
    detailList.value = response.data;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    inventoryCheckDetailId: null,
    checkId: null,
    assetId: null,
    foundLocationId: null,
    locationId: null,
    systemQuantity: null,
    actualQuantity: null,
    status: null,
    difference: null,
    batchNo: null,
    discrepancyNote: null
  };
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.value.pageNum = 1;
  console.log(queryParams)
  const result = await checkAssetList({
    checkId: route.query.id,
    actualQuantity: queryParams.value.actualQuantity
  })
  if (result?.code === 200) {
    detailList.value = result.data
  }
  console.log(result)
}

/** 重置按钮操作 */
function resetQuery() {
  data.queryParams = {
    actualQuantity: null,
  }
  getList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.inventoryCheckDetailId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加盘点单明细";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _inventoryCheckDetailId = row.inventoryCheckDetailId || ids.value
  getDetail(_inventoryCheckDetailId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改盘点单明细";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["detailRef"].validate(valid => {
    if (valid) {
      if (form.value.inventoryCheckDetailId != null) {
        updateDetail(form.value).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDetail(form.value).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _inventoryCheckDetailIds = row.inventoryCheckDetailId || ids.value;
  proxy.$modal.confirm('是否确认删除盘点单明细编号为"' + _inventoryCheckDetailIds + '"的数据项？').then(function() {
    return delDetail(_inventoryCheckDetailIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('check/detail/export', {
    ...queryParams.value
  }, `detail_${new Date().getTime()}.xlsx`)
}



onMounted(() => {
  console.log('接收到的盘点单route:', route)
  const checkId = route.query.id
  console.log('接收到的盘点单ID:', checkId)
  queryParams.value.checkId = checkId
  getList();

  // 可以在这里调用 getList() 并传入 checkId 过滤数据
})
</script>
